package com.eimf.saf.security.filter;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.eimf.saf.common.service.AccessLogService;

/**
 * @author eden
 * @date 2013-11-16 下午5:14:24
 * @Description: 通过Spring AOP来添加系统日志
 */
@Component
public class OperateLogIntercept
{
    private static final long serialVersionUID = 1L;

    @Autowired
    private AccessLogService accessLogSer;

    private static Log logger = LogFactory.getLog(OperateLogIntercept.class);

    public Object doSystemLog(final ProceedingJoinPoint point) throws Throwable
    {
        final HttpServletRequest request = ServletActionContext.getRequest();
        final String contentType = request.getContentType();
        final boolean ignoreLog = (contentType != null) && (contentType.startsWith("multipart/form-data"));
        final boolean exclude = true;
        if ((!ignoreLog) && (!exclude))
        {
            final long start = System.currentTimeMillis();
            preLog(request);
            OperateLogIntercept.logger.debug("LogFilter.preLog(" + request.getServletPath() + ") used:"
                    + (System.currentTimeMillis() - start));
        }
        final Object obj = point.proceed();
        if ((!ignoreLog) && (!exclude))
        {
            final long start = System.currentTimeMillis();
            postLog(request);
            OperateLogIntercept.logger.debug("LogFilter.postLog(" + request.getServletPath() + ") used:"
                    + (System.currentTimeMillis() - start));
        }
        return obj;
    }

    private void preLog(final HttpServletRequest req)
    {
        try
        {
            this.accessLogSer.addPreLog(req);
        } catch (final Exception e)
        {
            OperateLogIntercept.logger.error("Filter中记录前置日志出错", e);
        }
    }

    private void postLog(final HttpServletRequest req)
    {
        try
        {
            this.accessLogSer.updPostLog(req);
        } catch (final Exception e)
        {
            OperateLogIntercept.logger.error("Filter中记录后置日志出错", e);
        }
    }
}
